package com.wsx.ones.monitor.core.netty.codec;

import com.wsx.ones.monitor.common.util.FinalStaticUtil;
import com.wsx.ones.monitor.core.codec.MessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 解码的netty核心实现
 * Created by wangshuaixin on 17/2/6.
 */
public class MessageDecoder extends ByteToMessageDecoder {

    private MessageCodec messageCodec;

    public MessageDecoder(MessageCodec messageCodec) {
        this.messageCodec = messageCodec;
    }

    /**
     * 解码功能的核心实现
     * @param channelHandlerContext
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < FinalStaticUtil.HEADER_LENGTH) {
            return;
        }

        //从初始位置开始读取数据
        byteBuf.markReaderIndex();
        int bodyLength = byteBuf.readInt();
        if (bodyLength < 0) {
            channelHandlerContext.close();
        }

        //后面的消息长度是都和传递的消息长度是否一致
        if (byteBuf.readableBytes() < bodyLength) {
            byteBuf.resetReaderIndex();
            return;
        }

        //读取实际数据
        byte[] bytes = new byte[bodyLength];
        byteBuf.readBytes(bytes);

        try {
            //调用真实的解码方法，将字节转换成相应的对象
            Object obj = messageCodec.decode(bytes);
            list.add(obj);
        } catch (Exception e) {

        }

    }
}
